package com.hxl.olympic.fragment;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hxl.okhttp.response.JsonResponseHandler;
import com.hxl.olympic.R;
import com.hxl.olympic.util.Constant;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;


public class RegisterFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_sendCode)
    TextView tvSendCode;
    @BindView(R.id.btn_next_step)
    Button btnNextStep;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    private String phone, code;
    private int time;
    private Timer timer;

    @Override
    public void initialize() {
        timer = new Timer();
    }

    @Override
    public void initViews() {

    }

    @Override
    public void initData() {
        tvTitle.setText(getResources().getString(R.string.phone_login));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    @OnClick({R.id.tv_sendCode, R.id.btn_next_step, R.id.img_back})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        fragmentManager.popBackStack();
                    }
                }, 500);
            case R.id.tv_sendCode:
                sendCode();
                break;
            case R.id.btn_next_step:
                register();
                break;
        }
    }

    private void register() {
        phone = etPhone.getText().toString().trim();
        String inputCode = etCode.getText().toString().trim();
        if (phone.equals("") || inputCode.equals("")) {
            XToast.info(activity, "手机号或验证码输入为空!", Toast.LENGTH_SHORT).show();
            return;
        } else if (phone.length() < 11 || inputCode.length() < 6) {
            XToast.info(activity, "手机号或验证码长度不正确!", Toast.LENGTH_SHORT).show();
            return;
        } else if (!code.equals(inputCode)) {
            XToast.info(activity, "验证码输入不正确!", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        dialog.show();
        app.getOkHttpUtils().post(Constant.BASE_URL + Constant.selectUserByPhone, params, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                XToast.warning(activity, "该手机号已被注册!", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                if (statusCode == 200) {
                    RegisterInfoFragment rif = new RegisterInfoFragment();
                    rif.setPhone(phone);
                    fragmentManager.beginTransaction().replace(R.id.layout_login, rif)
                            .addToBackStack(null)
                            .commit();
                } else {
                    XToast.error(activity, "网络请求失败!", Toast.LENGTH_SHORT).show();
                }
                dialog.cancel();
            }
        });
    }

    private void sendCode() {
        phone = etPhone.getText().toString().trim();
        if (phone.equals("")) {
            XToast.info(activity, "手机号输入为空!", Toast.LENGTH_SHORT).show();
            return;
        } else if (phone.length() < 11) {
            XToast.info(activity, "请输入11位手机号!", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        System.out.println(code);
        params.put("code", code);
        tvSendCode.setEnabled(false);
        app.getOkHttpUtils().post(Constant.BASE_URL + Constant.sendCode, params, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                try {
                    JSONObject json = new JSONObject(response.toString());
                    if (json.getString("Message").equals("OK")) {
                        XToast.success(activity, "短信验证码发送成功!", Toast.LENGTH_SHORT).show();
                        time = 60;
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                handler.sendEmptyMessage(1);
                            }
                        }, 0, 1000);
                    } else {
                        Toast.makeText(activity, json.getString("Message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                XToast.error(activity, "网络请求失败!", Toast.LENGTH_SHORT).show();
                tvSendCode.setEnabled(true);
                tvSendCode.setText("重新发送");
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (time == 0) {
                        timer.cancel();
                        tvSendCode.setEnabled(true);
                        tvSendCode.setText("获取验证码");
                        return;
                    }
                    tvSendCode.setText("重新获取(" + time + ")");
                    --time;
                    break;
            }
        }
    };

}
